package com.run.runbbs.controller;


import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

@RestController
public class DownloadFileController {
    @Autowired
    ResourceLoader resourceLoader;

    @GetMapping("/down/{fileName}")
    public void downloadFile(@PathVariable(name = "fileName") String name,HttpServletResponse httpServletResponse) throws UnsupportedEncodingException, FileNotFoundException {
        //定义文件名和文件地址
        String fileName = name;
        String downloadUrl = "/data-center-pdf/"+fileName;
        Resource resource = null;
        try {
            //获取资源文件
            resource = resourceLoader.getResource("classpath:" + downloadUrl);
        } catch (Exception e) {
            //自定义业务异常
//            throw new BusinessException(201, "导出模板失败");
            System.out.println(e.getMessage());
        }
        //设置响应类型
        httpServletResponse.setContentType("application/msword");
        httpServletResponse.addHeader("Content-Disposition",
                " attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        //获取资源文件输入流和httpServletResponse的输出流
        if (Objects.nonNull(resource)) {
            try (InputStream inputStream = resource.getInputStream(); ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream()) {
                //把资源文件的二进制流数据copy到response的输出流中
                IOUtils.copy(inputStream, servletOutputStream);
                //清除flush所有的缓冲区中已设置的响应信息至客户端
                httpServletResponse.flushBuffer();
            } catch (Exception e) {
                //错误日志记录
                System.out.println(e.getMessage());
            }
        }
    }
}
